<template>
  <el-container class="outer">
    <!-- 侧边栏 -->
    <el-aside :width="'1'" style="background-color: #20222c">
      <!-- 折叠按钮 -->
      <div
        style="
          height: 60px;
          line-height: 60px;
          text-align: right;
          color: #fff;
          font-size: 20px;
          margin-right: 24px;
        "
      >
        <el-icon @click="isCollapse = !isCollapse">
          <Expand v-if="isCollapse"></Expand>
          <Fold v-else></Fold>
        </el-icon>
      </div>
      <el-menu
        active-text-color="#ffd04b"
        background-color="#20222c"
        class="el-menu-vertical-demo"
        default-active="/charts"
        text-color="#fff"
        :collapse="isCollapse"
        @select="handleMenu"
      >
        <!-- 动态生成菜单 -->
        <!-- 父菜单内容 -->
        <el-sub-menu
          v-for="(menu, index) in menuData"
          :index="index.toString()"
        >
          <template #title>
            <component
              class="icons"
              :is="menu.icon"
              style="width: 1em; height: 1em; margin-right: 8px"
            >
            </component>
            <span>{{ menu.name }}</span>
          </template>
          <!-- 子菜单内容 -->
          <el-menu-item
            v-for="(child, ind) in menu.children"
            :index="child.path"
          >
            <el-icon><component :is="child.icon"> </component></el-icon>
            <span>{{ child.name }}</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>

    <el-container class="main-container">
      <!-- 头部 -->
      <el-header class="header">
        <div class="mb">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item
              style="font-size: 15px; line-height: 70px"
              v-for="(item, index) in breadcrumbList"
              :key="index"
              :to="{ path: index === 0 ? '/' : item.path }"
            >
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="avatar">
          <img src="../../assets/images/avatar.gif" alt="avatar" />
        </div>
        <div class="session">
          <el-menu
            background-color="#f3f8fe"
            style="width: 100%; height: 68px"
            mode="horizontal"
            :ellipsis="false"
            @select="AdminMenuSelect"
          >
            <el-sub-menu index="admin">
              <!-- TODO -->
              <template #title> {{ userName }} </template>
              <el-menu-item index="editInfo">修改信息</el-menu-item>
              <el-menu-item index="logout">退出</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </div>
      </el-header>
      <!-- 主体 -->
      <el-main class="main-content">
        <el-tabs
          v-model="activeTab"
          type="card"
          closable
          @tab-click="handleTabClick"
          @tab-remove="removeTab"
          style="background-color: #fff; border-bottom: 1px solid #dcdcdc"
        >
          <el-tab-pane
            v-for="(tab, index) in tabs"
            :key="index"
            :label="tab.label"
            :name="tab.name"
          >
            <transition name="slide-right" mode="out-in">
              <router-view :key="tab.name"></router-view>
            </transition>
          </el-tab-pane>
        </el-tabs>
      </el-main>
      <!-- 页脚 -->
      <el-footer class="footer">
        <p>2025 Plain-Admin By HWZ.</p>
      </el-footer>
    </el-container>
  </el-container>

  <!-- 用户修改表单弹窗 -->
  <el-dialog
    v-model="show"
    title="修改管理员信息"
    width="500"
    draggable
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form ref="sfRef" :model="afm">
      <el-form-item
        label="用户名:"
        label-width="100"
        prop="loginName"
        style="width: 80%"
        :rules="[
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur',
          },
        ]"
      >
        <el-input v-model="afm.loginName" :disabled="true" />
      </el-form-item>

      <el-form-item
        label="登陆昵称:"
        label-width="100"
        prop="nickName"
        style="width: 80%"
      >
        <el-input v-model="afm.nickName" />
      </el-form-item>

      <el-form-item
        label="密码:"
        label-width="100"
        prop="loginPassword"
        style="width: 80%"
      >
        <el-input v-model="afm.loginPassword" />
      </el-form-item>
    </el-form>
    <!-- 对话框按钮，#插槽: 组件空出来，允许用户更改组件内容。由组件使用者定义 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import router from "@/router/index.js";
import { ArrowRight } from "@element-plus/icons-vue";
import userNameApi from "@/api/UserNameApi.js";
import studentApi from "@/api/StudentApi.js";
import jwtApi from "@/api/JwtApi.js";
//引入ElMessage
import { ElMessage } from "element-plus";
const activeIndex = ref("1");
//引入studentApi
import researchersApi from "/src/api/ResearcherApi.js";

// 研究人员（老师）菜单
const researcherMenuData = ref([
  {
    name: "首页",
    icon: "HomeFilled",
    path: "/researcher",
    children: [
      { name: "仪表盘", icon: "HomeFilled", path: "/researcher/dashboard" },
    ],
  },
  {
    name: "植物管理",
    icon: "GobletFull",
    children: [
      { name: "植物信息", icon: "GobletSquareFull", path: "/researcher/plant" },
      {
        name: "植物分类",
        icon: "GobletSquareFull",
        path: "/researcher/plantClassification",
      },
      {
        name: "种植方式",
        icon: "GobletSquareFull",
        path: "/researcher/plantMethod",
      },
      {
        name: "表型信息",
        icon: "GobletSquareFull",
        path: "/researcher/phenotypicData",
      },
    ],
  },
  {
    name: "植物识别",
    icon: "Notebook",
    children: [
      {
        name: "植物识别",
        icon: "Document",
        path: "/researcher/plantRecognition",
      },
    ],
  },
  {
    name: "课题管理",
    icon: "User",
    children: [
      { name: "选择实验", icon: "UserFilled", path: "/researcher/project" },
    ],
  },
  {
    name: "文献检索",
    icon: "Avatar",
    children: [
      { name: "在线检索", icon: "List", path: "/researcher/literature" },
    ],
  },
  {
    name: "用户管理",
    icon: "User",
    children: [
      { name: "导师管理", icon: "User", path: "/researcher/researcher" },
      { name: "学生管理", icon: "User", path: "/researcher/student" },
    ],
  },
  {
    name: "数据统计",
    icon: "Setting",
    children: [
      { name: "数据报表", icon: "Setting", path: "/researcher/setting" },
    ],
  },
  {
    name: "智能助手",
    icon: "ChatDotRound",
    children: [
      {
        name: "植物AI助手",
        icon: "ChatLineRound",
        path: "/researcher/plantAI",
      },
    ],
  },
]);

// 学生菜单
const studentMenuData = ref([
  {
    name: "首页",
    icon: "HomeFilled",
    path: "/student",
    children: [
      { name: "仪表盘", icon: "HomeFilled", path: "/student/dashboard" },
    ],
  },
  {
    name: "植物管理",
    icon: "GobletFull",
    children: [
      { name: "植物信息", icon: "GobletSquareFull", path: "/student/plant" },
      {
        name: "植物分类",
        icon: "GobletSquareFull",
        path: "/student/plantClassification",
      },
      {
        name: "种植方式",
        icon: "GobletSquareFull",
        path: "/student/plantMethod",
      },
      {
        name: "表型信息",
        icon: "GobletSquareFull",
        path: "/student/phenotypicData",
      },
    ],
  },
  {
    name: "植物识别",
    icon: "Notebook",
    children: [
      { name: "植物识别", icon: "Document", path: "/student/plantRecognition" },
    ],
  },
  {
    name: "课题管理",
    icon: "User",
    children: [
      { name: "选择实验", icon: "UserFilled", path: "/student/project" },
      { name: "我的课题", icon: "UserFilled", path: "/student/myProject" },
      { name: "实验进展", icon: "UserFilled", path: "/student/experiment" },
    ],
  },
  {
    name: "文献检索",
    icon: "Avatar",
    children: [{ name: "在线检索", icon: "List", path: "/student/literature" }],
  },
  {
    name: "数据统计",
    icon: "Setting",
    children: [{ name: "数据报表", icon: "Setting", path: "/student/setting" }],
  },
  {
    name: "智能助手",
    icon: "ChatDotRound",
    children: [
      {
        name: "植物AI助手",
        icon: "ChatLineRound",
        path: "/student/plantAI",
      },
    ],
  },
]);
// 定义响应式的菜单数据
const menuData = ref([]);
// 根据用户角色决定使用哪个菜单
// 在组件加载时根据用户类型设置正确的菜单
onMounted(() => {
  const userType = localStorage.getItem("userType");
  if (userType === "researcher") {
    menuData.value = researcherMenuData.value;
  } else {
    menuData.value = studentMenuData.value;
  }
});

// 面包屑
const breadcrumbList = ref([]);

// 创建面包屑的方法
function createBreadcrumb(path) {
  let matched = [];
  menuData.value.forEach((menu) => {
    if (menu.children) {
      const child = menu.children.find((c) => c.path === path);
      if (child) {
        matched = [
          { name: menu.name, path: menu.path },
          { name: child.name, path: child.path },
        ];
      }
    } else if (menu.path === path) {
      matched = [{ name: menu.name, path: menu.path }];
    }
  });
  return matched;
}

// 监听路由变化，更新面包屑
router.afterEach((to) => {
  breadcrumbList.value = createBreadcrumb(to.path);
});

// 页面加载时初始化面包屑
onMounted(() => {
  const currentPath = router.currentRoute.value.path;
  breadcrumbList.value = createBreadcrumb(currentPath);
});

// 用户下拉菜单的点击
function handleSelect(key, keyPath) {
  if (key == "logout") {
    // 用户退出
    logout();
  }
}
// 左侧菜单动作
function handleMenu(key) {
  if (key) {
    router.push(key);
  }
}
const isCollapse = ref(false);

// 点击用户菜单时触发
function AdminMenuSelect(menu) {
  if (menu === "logout") {
    jwtApi.remove(); // 删除jwt
    userNameApi.remove(); //删除用户名
    router.push("/login");
  }
  if (menu === "editInfo") {
    // userName
    show.value = true;
  }
}
// 取出用户名完成数据响应
const userName = userNameApi.get();

// 对话框是否显示
const show = ref(false);
let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
}
// 定义对话框内容
const adminFormModel = ref({
  loginName: "",
  loginPassword: "",
  nickName: "",
});
// 对话框内容别名
const afm = adminFormModel;
researchersApi.findByUserName(userName).then((resp) => {
  console.log("导师", resp);
  if (resp.code == 200) {
    afm.value = resp.data;
  } else {
    ElMessage({
      type: "error",
      message: "用户信息查询失败",
    });
  }
});

// 提交表单
function submitForm() {
  let admin = afm.value;
  //修改
  studentApi.update(admin).then((resp) => {
    console.log(resp);
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      window.location.reload();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

// 标签页管理
const tabs = ref([{ label: "首页", name: "/researcher/dashboard" }]);
const activeTab = ref("/researcher/dashboard");
const tabKey = ref(0);

// 添加新标签页
function addTab(name, label) {
  tabs.value.push({ label, name });
  activeTab.value = name;
  tabKey.value++;
}

// 移除标签页
function removeTab(name) {
  tabs.value = tabs.value.filter((tab) => tab.name !== name);
  if (tabs.value.length > 0) {
    activeTab.value = tabs.value[0].name;
  } else {
    activeTab.value = "/researcher/dashboard";
  }
}

// 监听路由变化，更新标签页
router.afterEach((to) => {
  const existingTab = tabs.value.find((tab) => tab.name === to.path);
  if (!existingTab) {
    addTab(to.path, to.meta.title || to.name || to.path);
  }
  activeTab.value = to.path;
});
// 处理标签页点击事件
function handleTabClick(tab) {
  console.log("Researcher Tab clicked:", tab);
  router.push(tab.paneName || tab.name);
}

// 页面加载时初始化标签页
onMounted(() => {
  const currentPath = router.currentRoute.value.path;
  const existingTab = tabs.value.find((tab) => tab.name === currentPath);
  if (!existingTab) {
    addTab(
      currentPath,
      router.currentRoute.value.meta.title ||
        router.currentRoute.value.name ||
        currentPath
    );
  }
  activeTab.value = currentPath;
});
</script>

<style scoped>
.outer {
  height: 100vh;
  border: 1px solid #ccc;
  display: flex;
}

.outer .el-main {
  padding: 0px;
}

.el-main {
  padding: 0px;
}

.el-menu {
  border-width: 0px;
}

.main-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

.header {
  background-color: #f3f8fe;
  border-bottom: 1px solid #999;
  height: 70px;
  display: flex;
  flex-direction: row;
}

.header > .mb {
  flex-grow: 1;
  line-height: 70px;
}

.header > .demo-type {
  flex-grow: 1;
  text-align: right;
  line-height: 70px;
}

.header > .session {
  flex-shrink: 0;
  height: 70px;
}

/* 自定义标签页样式 */
.el-tabs__nav-wrap {
  background-color: #fff; /* 标签页背景颜色设置为白色 */
  border-bottom: 1px solid #dcdcdc; /* 底部边框颜色和宽度 */
}

.el-tabs__item {
  color: #333; /* 标签页字体颜色 */
  border: 1px solid transparent; /* 标签页边框颜色 */
  border-radius: 4px 4px 0 0; /* 标签页圆角 */
  padding: 10px 20px; /* 标签页内边距 */
  transition: all 0.3s; /* 标签页过渡效果 */
  position: relative; /* 为伪元素定位 */
}

.el-tabs__item:hover {
  background-color: #e4e7ed; /* 鼠标悬停时的背景颜色 */
}
/**
 * 激活标签页样式，底部下划线蓝色
 */
.el-tabs__item.is-active {
  background-color: #fff; /* 激活标签页的背景颜色 */
  color: #409eff; /* 激活标签页的字体颜色 */
  border-bottom-color: #409eff; /* 激活标签页的底部边框颜色 */
  border-top: 2px solid #409eff; /* 激活标签页的顶部边框颜色 */
}

.el-tabs__item.is-active::after {
  content: ""; /* 必须有内容 */
  position: absolute;
  bottom: -1px; /* 调整下划线的位置 */
  left: 0;
  right: 0;
  height: 2px; /* 下划线高度 */
  background-color: #409eff; /* 下划线颜色 */
  border-radius: 0; /* 下划线圆角 */
}

/* 自定义标签页内容区域样式 */
.el-tab-pane {
  background-color: #fff; /* 标签页内容区域背景颜色 */
  padding: 20px; /* 标签页内容区域内边距 */
  border: 1px solid #dcdcdc; /* 标签页内容区域边框颜色 */
  border-top: none; /* 去掉顶部边框 */
}

/* 自定义主体内容样式 */
.main-content {
  flex: 1; /* 占据剩余空间 */
  padding: 20px; /* 主体内容内边距 */
  overflow-y: auto; /* 溢出时滚动 */
}

/* 自定义页脚样式 */
.footer {
  background-color: #f3f8fe; /* 页脚背景颜色 */
  color: #606266; /* 页脚字体颜色 */
  text-align: center; /* 页脚文本居中 */
  padding: 10px 0; /* 页脚内边距 */
  border-top: 1px solid #dcdcdc; /* 页脚顶部边框 */
  height: 50px;
}
.footer p {
  margin: 0;
  font-size: 14px;
  line-height: 25px;
  color: #606266;
}

/* 定义滑动动画 */
@keyframes slideIn {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(0);
  }
}
@keyframes slideOut {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-100%);
  }
}
/* 定义滑动动画的类 */
.slide-in {
  animation: slideIn 0.5s ease-out forwards;
}
.slide-out {
  animation: slideOut 0.5s ease-in-out forwards;
}
</style>


<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 50%;
  margin-top: 15px;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
